package jindu.zzh.gj.jinduriddle.riddle.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechError;

import jindu.zzh.gj.jinduriddle.R;
import jindu.zzh.gj.jinduriddle.riddle.Myapplication;
import jindu.zzh.gj.jinduriddle.riddle.aiui.IseUtils;
import jindu.zzh.gj.jinduriddle.riddle.aiui.SpeakHandler;
import jindu.zzh.gj.jinduriddle.riddle.aiui.TTSUtils;
import jindu.zzh.gj.jinduriddle.riddle.entity.QuestionBean;
import jindu.zzh.gj.jinduriddle.riddle.utils.ToastUtils;
import jindu.zzh.gj.jinduriddle.riddle.xml.Result;
import jindu.zzh.gj.jinduriddle.riddle.xml.XmlResultParser;


public class PagerFragment extends Fragment {

    private QuestionBean questionBean;
    private TextView tv_question_text;
    private TextView tv_choice1, tv_choice2;


    public static PagerFragment newInstance(QuestionBean questionBean) {

        Bundle args = new Bundle();
        args.putSerializable("questionBean", questionBean);

        PagerFragment fragment = new PagerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getContext(), R.layout.pager_riddle, null);
        init(view);
        return view;
    }


    private void init(View root) {
        ((MainRiddleActivity) getActivity()).reset();  //重置状态
        ((MainRiddleActivity) getActivity()).startCountDown();  //开始计时
        questionBean = (QuestionBean) getArguments().getSerializable("questionBean");
        Log.d("TAG", "init: " + questionBean.getQuestion());
        tv_question_text = root.findViewById(R.id.tv_questiontext);
        tv_question_text.setTypeface(((MainRiddleActivity) getActivity()).tfXingKai);
        ((TextView) root.findViewById(R.id.tvtoptip)).setTypeface(((MainRiddleActivity) getActivity()).tfXingKai);
        Log.d("TAG5", "第" + Myapplication.currentConut);
        tv_question_text.setText(questionBean.getQuestion());
        tv_choice1 = root.findViewById(R.id.tv_choice1);
        tv_choice1.setTypeface(((MainRiddleActivity) getActivity()).tfXingKai);
        tv_choice1.setText(questionBean.getChoice1());
        tv_choice2 = root.findViewById(R.id.tv_choice2);
        tv_choice2.setTypeface(((MainRiddleActivity) getActivity()).tfXingKai);
        tv_choice2.setText(questionBean.getChoice2());
        setTextVisible(true);

//        final Button bt = root.findViewById(R.id.bt_startAnswer);
//        bt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                bt.setClickable(false);
//                bt.setVisibility(View.INVISIBLE);
//                setTextVisible(true);
//                speak();
//                startIseEvaluating();
//            }
//        });
    }

    private void setTextVisible(boolean b) {
        if (tv_choice1 == null || tv_choice2 == null || tv_question_text == null) return;
        int visible = b ? View.VISIBLE : View.INVISIBLE;
        tv_question_text.setVisibility(visible);
        tv_choice1.setVisibility(visible);
        tv_choice2.setVisibility(visible);
    }

    //开始评测
    public void startIseEvaluating() {
        if (questionBean != null) {
            IseUtils.getInstance(getContext()).startIseEvaluating(questionBean.getAnswer(), new myEvaluatorListener());
        }
    }

    //开始发声
    public void speak(SpeakHandler speakHandler) {
        if (questionBean != null) {
            Log.d("TAG", "speak: " + questionBean.getQuestion());
            TTSUtils.getInstance(getContext()).startSpeak(questionBean.getQuestion(), speakHandler);
        }
    }

    //评测回调接口
    class myEvaluatorListener implements EvaluatorListener {

        @Override
        public void onVolumeChanged(int i, byte[] bytes) {

        }

        @Override
        public void onBeginOfSpeech() {
            if (getActivity() == null) return;
            ((MainRiddleActivity) getActivity()).speechView.setVisibility(View.VISIBLE);
            //ToastUtils.getInstance(getContext().getApplicationContext()).showShortToast("检测到开始回答..");
        }

        @Override
        public void onEndOfSpeech() {
            if (getActivity() == null) return;
            ((MainRiddleActivity) getActivity()).speechView.setVisibility(View.INVISIBLE);
            ((MainRiddleActivity) getActivity()).cancelCountDown();
            ToastUtils.getInstance(getContext().getApplicationContext()).showShortToast("正在检测答案...");
        }

        @Override
        public void onResult(EvaluatorResult evaluatorResult, boolean isLast) {
            if (isLast) {
                String resultStr = evaluatorResult.getResultString();
                if (!TextUtils.isEmpty(resultStr)) {
                    judgeResult(resultStr);
                }
            }
        }


        @Override
        public void onError(SpeechError speechError) {
            Log.d("TAG5", "SpeechError " + speechError.getErrorDescription());
            TTSUtils.getInstance(getContext()).startSpeak("网络连接不顺畅，分析不到声音", null);
            ToastUtils.getInstance(getContext().getApplicationContext()).showShortToast("网络连接不顺畅，分析不到声音");
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    }

    private void judgeResult(String resultStr) {

        XmlResultParser resultParser = new XmlResultParser();
        Result result = resultParser.parse(resultStr);
        float total_score = result.total_score;
        Log.e("TAG5", "result :" + result.toString());
        if (total_score > 2.8) {
            //ToastUtils.getInstance(getContext()).showShortToast("回答正确" + result.total_score);
            ToastUtils.getInstance(getContext()).showShortToast("回答正确");
            Log.d("TAG", "回答正确:" + total_score);
            String tip = "回答正确,请看下一题";

            if (Myapplication.currentConut == 3) {
                tip = "回答正确。答题完成，欢迎下次继续玩呢";
                TTSUtils.getInstance(getContext()).startSpeak(tip, new SpeakHandler() {
                    @Override
                    public void onSpeakBegin() {

                    }

                    @Override
                    public void onCompleted(SpeechError var1) {
                        Intent intent = new Intent(getActivity(), OverActivity.class);
                        //intent.putExtra("desc", "恭喜挑战成功");
                        startActivity(intent);
                        getActivity().finish();
                    }
                });
            } else {
                TTSUtils.getInstance(getContext()).startSpeak(tip, new SpeakHandler() {
                    @Override
                    public void onSpeakBegin() {

                    }

                    @Override
                    public void onCompleted(SpeechError var1) {
                        ((MainRiddleActivity) getActivity()).changeNext(getView());
                    }
                });
            }


        } else {
            ++Myapplication.error;
            if (Myapplication.currentConut < 3) {
                String tip = "回答错误,正确答案是" + questionBean.getAnswer() + ",继续下一题吧";
                if (result.time_len < 100 || result.time_len > 800) {
                    tip = "不好意思，我没听清楚,再来一题吧";
                }
                ToastUtils.getInstance(getContext()).showShortToast(tip);
                Log.d("TAG", "回答错误:" + total_score + " , timelen: " + result.time_len);
                TTSUtils.getInstance(getContext()).startSpeak(tip, new SpeakHandler() {
                    @Override
                    public void onSpeakBegin() {

                    }

                    @Override
                    public void onCompleted(SpeechError var1) {
                        ((MainRiddleActivity) getActivity()).changeNext(getView());
                    }
                });

            } else {
                String tip = "回答错误,正确答案是" + questionBean.getAnswer();
                if (result.time_len < 100 || result.time_len > 800) {
                    tip = "抱歉我没听清楚";
                }
                TTSUtils.getInstance(getContext()).startSpeak(tip + "，答题结束,下次再玩啦。", new SpeakHandler() {
                    @Override
                    public void onSpeakBegin() {

                    }

                    @Override
                    public void onCompleted(SpeechError var1) {
                        startActivity(new Intent(getActivity(), OverActivity.class));
                        getActivity().finish();
                    }
                });

            }

        }
    }
}
